﻿using PwjCy.Lite.Common;
using PwjCy.Lite.Core;
using PwjCy.Lite.Core.Imp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace PwjCy.Lite.PwjcyCache.Imp
{
    public class CacheService : ICacheService
    {
        private Cache _LocalCache
        {
            get { return HttpRuntime.Cache; }
        }
        private CacheConfig _CacheConfig
        {
            get { return LiteCoreHelper.GetObjectSetting<CacheConfig>(LiteCoreHelper.CacheConfigPath); }
        }
        public void Add<T>(T obj, string key, int expireSeconds)
        {
            _LocalCache.Insert(key, obj, null, DateTime.Now.AddSeconds(expireSeconds), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        public void Add<T>(T obj, string key)
        {
            Add<T>(obj, key, _CacheConfig.DefaultExpireSeconds);
        }

        public T GetCacheOjbect<T>(string key)
        {
            try
            {
                object obj = _LocalCache.Get(key);
                if (null == obj)
                {
                    throw new Exception(string.Format("no found CacheObject,key:{0}", key));
                }
                return (T)obj;
            }
            catch (Exception ex)
            {
                ServiceHub.LoggerService.Error(string.Format("while WolfLiteLocalCache GetCacheObject Error,{0}", ex));
                return default(T);
            }
        }

        public void RemoveCache(params string[] key)
        {
            try
            {
                foreach (var k in key)
                {
                    _LocalCache.Remove(k);
                }
            }
            catch (Exception ex)
            {
                ServiceHub.LoggerService.Error(string.Format("while WolfLiteLocalCache RemoveCache Error,{0}", ex));
            }
        }
    }
}
